package com.mumux.utils;

import com.mumux.template.MumuxTemplate;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

/**
 * Created by cong on 2019/4/21.
 */
public class CreateUtil {

    public static void createController(MumuxTemplate mumuxTemplate){
        String filePath = mumuxTemplate.getPackagePath() + "controller";
        String fileName = mumuxTemplate.getEntityClassName() + "Controller.java";
        createJavaFile(mumuxTemplate,filePath,fileName);
    }
    public static void createEntity(MumuxTemplate mumuxTemplate){
        String filePath = mumuxTemplate.getPackagePath() + "entity";
        String fileName = mumuxTemplate.getEntityClassName() + ".java";
        createJavaFile(mumuxTemplate,filePath,fileName);
    }
    public static void createServiceInterface(MumuxTemplate mumuxTemplate){
        String filePath = mumuxTemplate.getPackagePath() + "service";

        String fileName = mumuxTemplate.getEntityClassName() + "Service.java";
        createJavaFile(mumuxTemplate,filePath,fileName);
    }
    public static void createDaoInterface(MumuxTemplate mumuxTemplate){
        String filePath = mumuxTemplate.getPackagePath() + "mapper";
        String fileName = mumuxTemplate.getEntityClassName() + "Mapper.java";
        createJavaFile(mumuxTemplate,filePath,fileName);
    }


    public static void createJavaFile(MumuxTemplate mumuxTemplate,String filePath,String fileName){
        try{
            //指定模板路径
            String root = System.getProperty("user.dir") + File.separator + "codeGenerator" + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "template" + File.separator;
            FileResourceLoader resourceLoader = new FileResourceLoader(root,"utf-8");
            Configuration cfg = Configuration.defaultConfiguration();
            GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
            //指定要加载的模板
            Template t = gt.getTemplate(mumuxTemplate.getTemplateName());
            //绑定全局变量
            t.binding("myUtil",mumuxTemplate);
            //读取模板输出的文本
            String str = t.render();
            System.out.println(str);
            File dir = new File(mumuxTemplate.getRootPath() + File.separator + filePath);
            if(!dir.exists() && !dir.isDirectory()){
                dir.mkdirs();
            }
            File file = new File( dir + File.separator + fileName );
            if(!file.exists()){
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(str);
            bw.flush();
            bw.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }

    }
    
}
